package com.ww.book.javaconcurrencyinpractice.ch03;

/**
 * 隐式this引用逃逸示例
 */
public class ImplicitEscape {
    private static ImplicitEscape escapeInstance;
    private final String data;

    public ImplicitEscape() {
        // 将this引用发布到静态变量中
        escapeInstance = this;

        // 模拟耗时初始化
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
        this.data = "数据初始化完成";
    }

    public String getData() {
        return data;
    }

    public static ImplicitEscape getInstance() {
        return escapeInstance;
    }

    public static void main(String[] args) throws InterruptedException {
        Thread t = new Thread(() -> {
            // 在另一个线程中访问可能尚未完全构造的对象
            ImplicitEscape instance = ImplicitEscape.getInstance();
            if (instance != null) {
                // 可能看到data = null
                System.out.println("Data: " + instance.getData());
            } else {
                System.out.println("未初始化完成");
            }
        });

        t.start();
        Thread.sleep(100);

        new ImplicitEscape(); // 构造对象

        t.join();
    }
}
